package com.example.coursedesign;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.coursedesign.dao.UserDao;

/**
 * function：连接页面加载首页
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "mysql-coursedesign-MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }

    public void reg(View view) {
        startActivity(new Intent(getApplicationContext(), register.class));
    }

    /**
     * function: 登录
     */
    public void login(View view) {
        EditText EditTextAccount = findViewById(R.id.uesrAccount);
        EditText EditTextPassword = findViewById(R.id.userPassword);

        String account = EditTextAccount.getText().toString().trim();
        String password = EditTextPassword.getText().toString().trim();
        if (account.isEmpty()&&account.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入用户信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (account.isEmpty()) {
            Toast.makeText(getApplicationContext(), "账号不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.isEmpty()) {
            Toast.makeText(getApplicationContext(), "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread() {
            @Override
            public void run() {
                UserDao userDao = new UserDao();
                int msg = userDao.login(account, password);
                hand1.sendEmptyMessage(msg);
            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    final Handler hand1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), "登录失败！", Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_LONG).show();
                    //登录成功跳转首页
                    Intent intent = new Intent(MainActivity.this, medicineRemind.class);
                    startActivity(intent);
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "密码错误！", Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(), "账号不存在！", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
}